package com.tradesolver;

import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Logger;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class HtmlServlet extends HttpServlet {
  Logger logger = Logger.getLogger(HtmlServlet.class.getName());

  Dao dao = new Dao();

  Cache cache;

  NumberFormat pf = new DecimalFormat("###,###.###");
  NumberFormat cf = new DecimalFormat("##.####");
  NumberFormat vf = new DecimalFormat("###,###,###,###.###");
  
//  @Override
//  public void init(ServletConfig config) {
//
//    try {
//        CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
//        cache = cacheFactory.createCache(Collections.emptyMap());
//    } catch (CacheException e) {
//        // ...
//    }
//  }
  
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    
    logger.info(req.getRequestURI());
    
    TreeSet<String> headers = new TreeSet<String>();
    TreeSet<String> tickers = new TreeSet<String>();
    TreeMap<String, TreeMap<String, UpdateData>> stockUpdates = new TreeMap<String, TreeMap<String, UpdateData>>();
    
    DateFormat yyyymmdd = new SimpleDateFormat("yyyyMMdd");
    Calendar day = Calendar.getInstance();
    List<StockUpdate> updates = dao.getStockUpdates(yyyymmdd.format(day.getTime()));
    
    
    for (StockUpdate update: updates) {
      
      TreeMap<String, UpdateData> stockUpdate = new TreeMap<String, UpdateData>();
      String[] tokens = update.data.split(";");
      for (int i=4; i<tokens.length;) {
        String ticker = tokens[i++].trim();
        
        if (ticker.length() > 5 || "PSEi".equals(ticker)) {
          ticker = "^" + ticker;
        }
        
        String[] pricePct = tokens[i++].split(" +");
        String name = tokens[i++];
        String volume = tokens[i++].trim();
        if (".".equals(volume)) volume = "0";
        
        try {
          UpdateData obj = new UpdateData(ticker, pf.parse(pricePct[0]).floatValue(), cf.parse(pricePct[1]).floatValue(), vf.parse(volume).longValue());
          stockUpdate.put(ticker, obj);
          tickers.add(ticker);
        } catch (ParseException e) {
          logger.severe(update.data);
          logger.severe(" stamp=[" + update.stamp +"]" +" ticker=[" + ticker +"]" + " pricePct=[" + pricePct[0] + "," + pricePct[1] +"]" + " volume=[" + volume +"]");
          throw new RuntimeException(e);
        }
        
      }
      
//      StockUpdate upd = updates.get(1);
//      StockUpdate newUpdate = new StockUpdate("201104191220", upd.data);
//      dao.putStockUpdate(newUpdate);
//      
//      
      headers.add(update.stamp.substring(8));
      stockUpdates.put(update.stamp.substring(8), stockUpdate);
    }
    
    req.setAttribute("myHeaders", headers);
    req.setAttribute("tickers", tickers);
    req.setAttribute("stockUpdates", stockUpdates);
    
    
    String nextJSP = "/WEB-INF/jsp/summary.jsp";
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
    try {
      dispatcher.forward(req,resp);
    } catch (ServletException e) {
      throw new RuntimeException(e);
    }
  }

}
